﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillData();
            }
        }
        private void FillData()
        {
            var sql = string.Format("select * from Articles");
            var dt = DbHelper.GetDataTable(sql);
            moon.DataSource = dt;
            moon.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            var sql = string.Format("select * from Articles");
            var dt = DbHelper.GetDataTable(sql);
            dt.Rows.Add(dt.NewRow());
            moon.DataSource = dt;
            moon.DataBind();
            moon.EditIndex = dt.Rows.Count - 1;
            moon.DataSource = dt;
            moon.DataBind();
        }

        protected void moon_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            moon.EditIndex = -1;
            FillData();
        }

        protected void moon_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetValue(e.RowIndex, 0);
            var sql = string.Format("delete from Articles where id='{0}'", id);
            DbHelper.AddOrDeleteOrUpdate(sql);
            moon.DataSource = -1;
            moon.DataBind();

        }

        private string GetValue(int rowIndex, int colIndex)
        {
            var ui = moon.Rows[rowIndex].Cells[colIndex];
            var value = ui.Controls.Count > 0 ? ((TextBox)ui.Controls[0]).Text : ui.Text;
            return value;
        }

        protected void moon_RowEditing(object sender, GridViewEditEventArgs e)
        {
            moon.EditIndex = e.NewEditIndex;
            FillData();
        }

        protected void moon_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var idString = GetValue(e.RowIndex, 0);
            var isOk = int.TryParse(idString, out int id);
            var title = GetValue(e.RowIndex, 1);
            var content = GetValue(e.RowIndex, 2);
            var author = GetValue(e.RowIndex, 3);
            var remarks = GetValue(e.RowIndex, 4);
            if (isOk)
            {
                var sql = string.Format("update Articles set Title='{0}',Content='{1}',Author='{2}',Remarks='{3}'where id={4}", title, content, author, remarks, id);
                DbHelper.AddOrDeleteOrUpdate(sql);
            }
            else
            {
                var sql = string.Format("insert into Articles(Title,Content,Author,Remarks)values('{0}','{1}','{2}','{3}')", title, content, author, remarks);
                DbHelper.AddOrDeleteOrUpdate(sql);
            }
            moon.EditIndex = -1;
            FillData();
        }
    }
}